'use strict'

const { Sequelize, DataTypes,Op } = require('sequelize');
const fs = require('fs')
const {db_dialect,db_database,db_host,db_username,db_password} = require('../config/db')

// 利用sequelize工具连接数据库 
// sequelize; pg pg-hstore
const sequelize = new Sequelize(db_database, db_username, db_password, {
    host: db_host,
    dialect: db_dialect
});

// 对model进行遍历，找出 .js结尾的，不是index.js的文件
let files = fs.readdirSync(__dirname)
let resFiles = files.filter(item => {
    return item.endsWith('.js') && item != 'index.js'
})


let resObj = {}
resFiles.forEach(item => {
    let modelName = item.replace('.js', '')
    console.log(modelName);
    let tmpObj = require(__dirname + '/' + item)
    // 这里需要的是模型的名称为modelName表示的值，而不是modelName本身被赋值为这个模型
    let tableName = modelName.toLowerCase()
    resObj[modelName] = sequelize.define(tableName, tmpObj)
    console.log(modelName);
})

resObj.Op = Op

// 将模型同步到数据库，重新封装一个异步函数，，如果需要才会给调用
resObj.sync=async()=>{
    // await 只用这个执行完成之后才会接着往下执行---针对异步执行
    sequelize.sync({force:true}).then(()=>{
        // 批量插入数据
        resObj.Users.bulkCreate([
            {
                username:'admin',
                password:'123',
                nickname:'超级管理员',
                avatar:'无'
            },
            {
                username:'user001',
                password:'234',
                nickname:'小楠',
                avatar:'无'
            },
            {
                username:'user002',
                password:'345',
                nickname:'小青',
                avatar:'无'
            },
        ])

        resObj.Products.bulkCreate([
            {
                name:'谷雨',
                date:'4月20日'
            },
            {
                name:'雨水',
                date:'2月19日'
            },
        ])
    })
}

module.exports = resObj